package com.ml.loan.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Slf4j
public enum AESUtil {
    //

    INSTANCE;

    /**
     * 数据中心加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
     */
    private static final String sKey = "IyfEQOTFrS8mL2p9";
    private static final String ivParameter = "3yO6XfsdmDzS3mjE";
    private static final int secretKeyLength = 16;
    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * 加密
     **/
    public String encrypt(String encData, String secretKey, String vector) {
        if (secretKey == null) {
            return null;
        }
        if (secretKey.length() != secretKeyLength) {
            return null;
        }
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            byte[] raw = secretKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec iv = new IvParameterSpec(vector.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(encData.getBytes(StandardCharsets.UTF_8));
            // 此处使用BASE64做转码。
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            log.error("AESUtil.encrypt:{}", e.getMessage(), e);
            return null;
        }
    }

    // 加密
    public String encrypt(String sSrc) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
            String str = Base64.getEncoder().encodeToString(encrypted);
            return sercert(str);
        } catch (Exception e) {
            log.error("AESUtil.encrypt:{}", e.getMessage(), e);
            return null;
        }
    }

    // 解密
    public String decrypt(String sSrc) {
        try {
            String str = restore(sSrc);
            byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            // 先用base64解密
            byte[] encrypted1 = Base64.getDecoder().decode(str);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, StandardCharsets.UTF_8);
            return originalString;
        } catch (Exception ex) {
            log.error("AESUtil.decrypt:{}", ex.getMessage(), ex);
            return null;
        }
    }

    public String decrypt(String sSrc, String key, String ivs) {
        try {
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            // 先用base64解密
            byte[] encrypted1 = Base64.getDecoder().decode(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, StandardCharsets.UTF_8);
            return originalString;
        } catch (Exception ex) {
            log.error("AESUtil.decrypt:{}", ex.getMessage(), ex);
            return null;
        }
    }

    public String sercert(String str) {
        //存储加密后的字符串
        StringBuffer str2 = new StringBuffer();
        //加密过程
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            str2.append(c);
        }
        return str2.toString();
    }

    /**
     * 解密
     */
    public String restore(String str) {
        StringBuffer str3 = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            str3.append(c);
        }
        return str3.toString();
    }

    public static void main(String[] args) throws Exception {
        // 需要加密的字串
        String cSrc = "123456";
        // 加密
        long lStart = System.currentTimeMillis();
        String enString = AESUtil.INSTANCE.encrypt(cSrc);
        System.out.println("加密后的字串是：" + enString);

        long lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("加密耗时：" + lUseTime + "毫秒");
        // 解密
        lStart = System.currentTimeMillis();
        String DeString = AESUtil.INSTANCE.decrypt(enString);
        System.out.println("解密后的字串是：" + DeString);
        lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("解密耗时：" + lUseTime + "毫秒");
    }
}
